// import 'es6-promise/auto'
import Vue from 'vue'
import Vuex from 'vuex'
import wx from 'weixin-js-sdk'
import Cookies from 'js-cookie'

Vue.use(Vuex)

import CONSTANT from '../components/constant'

const state = {
    routerTo: sessionStorage.getItem('routerTo') || '',
    // 是否中粮用户
    memberDetail: sessionStorage.getItem('memberDetail') || 0,
    //礼品code
    giftCode: sessionStorage.getItem('giftCode') || '',
    //购物车商品数量
    cartGoodsNum: sessionStorage.getItem('cartGoodsNum') || 0,
    // 商品详情
    imglist: sessionStorage.getItem('imglist') || [],
    love: sessionStorage.getItem('love') || 0,
    city: sessionStorage.getItem('city') || null,
    // 央联易信的TOKEN
    token: Cookies.get('token') || null,
    userid: Cookies.get('userid') || '',
    openId: Cookies.get('openId') || '',
    mobPhone: Cookies.get('mobPhone') || '',
    // 企业微信登录、微信公众号登录的区分
    inMode: Cookies.get('inMode') || '',
    // 商品详情页面是否进入
    detailPage: Cookies.get('detailPage') || '',
    // 页面多个Tab时，当前选中的tab
    selectedTab: Cookies.get('selectedTab') || 0, 
    // 页面跳转处理flg  A页面->B页面
    pageToPage: Cookies.get('pageToPage') || '',
    // 页面跳转处理时需要保存的参数
    pageParams: Cookies.get('pageParams') || '',
    // 页面跳转时滚动条的位置
    scrollPostion: Cookies.get('scrollPostion') || 0,
    url: Cookies.get('url') || '',
    scrolls: [],
    scrollsbox: [],
    searchValue: '',
    searchLove: '',
    startPrice: 0,
    endPrice: 100
}

//改变状态
const mutations = {
    routerTo(state, opt) {
        sessionStorage.setItem('routerTo', opt)
        state.routerTo = opt;
    },
    memberDetail(state, opt) {
        sessionStorage.setItem('memberDetail', opt)
        state.memberDetail = opt;
    },
    giftCode(state, opt) {
        sessionStorage.setItem('giftCode', opt)
        state.giftCode = opt;
    },
    cartGoodsNum(state, opt) {
        sessionStorage.setItem('cartGoodsNum', opt)
        state.cartGoodsNum = opt;
    },
    imglist(state, opt) {
        sessionStorage.setItem('imglist', opt)
        state.imglist = opt;
    },
    love(state, opt) {
        sessionStorage.setItem('love', opt)
        state.love = opt
    },
    citys(state, opt) {
        sessionStorage.setItem('city', opt)
        state.city = opt;
    },
    token(state, opt) {
        //一个月内免密登录
        Cookies.set('token', opt, {expires: 30, path: ''});
        state.token = opt
    },
    userid(state, opt) {
        // Create an expiring cookie, valid to the path of the current page:
        //      Cookies.set('name', 'value', { expires: 7, path: '' });
        // Create a cookie that expires 7 days from now, valid across the entire site:
        //      Cookies.set('name', 'value', { expires: 7 });
        // 当设置的失效时间大于等于1天时，我们可以在 expires 属性后面直接输入XX天数
        //      Cookies.set('name', 'value', {expires: 7});  
        // 当设置的失效时间少于一天时：我们需要在当前的时间上加上失效时间（下面是设置cookie的失效时间为15分钟）
        //      var millisecond = new Date().getTime();  
        //      var expiresTime = new Date(millisecond + 60 * 1000 * 15);
        //      Cookies.set('name', 'value', {expires: expiresTime}); 
        Cookies.set('userid', opt, {expires: 30, path: ''}); //一个月内免密登录
        state.userid = opt
    },
    openId(state, opt) {
        //Cookies.set('openId', opt, {expires: 7, path: ''}); //7天过期
        //一个月内免密登录
        Cookies.set('openId', opt, {expires: 30, path: ''}); 
        state.openId = opt
    },
    mobPhone(state, opt) {
        Cookies.set('mobPhone', opt);
        state.mobPhone = opt
    },
    inMode(state, opt) {
        Cookies.set('inMode', opt);
        state.inMode = opt
    },
    detailPage(state, opt) {
        Cookies.set('detailPage', opt);
        state.detailPage = opt
    },
    selectedTab(state, opt) {
        Cookies.set('selectedTab', opt);
        state.selectedTab = opt
    },
    pageToPage(state, opt) {
        Cookies.set('pageToPage', opt);
        state.pageToPage = opt
    },
    pageParams(state, opt) {
        Cookies.set('pageParams', opt);
        state.pageParams = opt
    },
    scrollPostion(state, opt) {
        Cookies.set('scrollPostion', opt);
        state.scrollPostion = opt
    },
    setUrl(state, opt) {
        Cookies.set('url', opt);
        state.url = opt
    },
    //删除token（通过拦截器引起的重新登陆的处理）
    tokenDel(state) {
        sessionStorage.setItem('cartGoodsNum', 0)
        state.cartGoodsNum = 0;
        Cookies.remove('token');
        state.token = null;
        Cookies.remove('userid');
        state.userid = '';
        Cookies.remove('selectedTab');
        state.selectedTab = 0;
        Cookies.remove('pageToPage');
        state.pageToPage = '';
        Cookies.remove('pageParams');
        state.pageParams = '';
        Cookies.remove('scrollPostion');
        state.scrollPostion = 0;
    },
    scrolls(state, opt) {
        state.scrolls = opt
    },
    scrollsbox(state, opt) {
        state.scrollsbox = opt
    },
    searchValue(state, opt) {
        state.searchValue = opt
    },
    searchLove(state, opt) {
        state.searchLove = opt
    },

    //分享
    scan(state, opt) {
        let href = encodeURIComponent(window.location.href.split('#')[0]); //url不能写死
        // 使用本页面定义的CONSTANT，不可使用this.CONSTANT
        Vue.prototype.$axios.get(CONSTANT.wapiBaseUrl + 'other/getWxAccess?url=' + href + '&inMode=' + state.inMode)
            .then((response) => {
                if (response.status == 200) {
                    if (response.data.status == 1) {
                        wx.config({
                            appId: response.data.object.appId,
                            timestamp: response.data.object.timeStamp,
                            nonceStr: response.data.object.nonceStr,
                            signature: response.data.object.signature,
                            jsApiList: [
                                'checkJsApi', //判断当前客户端版本是否支持指定JS接口
                                'onMenuShareTimeline', //分享到朋友圈
                                'onMenuShareAppMessage' //分享给好友
                            ]
                        })
                        wx.ready(() => {
                            let title = '中粮员工关爱平台';
                            let link = window.location.href.split('#')[0];
                            let desc = '一个有温度的社群';
                            //let imgUrl = 'http://img.youlanw.com/o/tmp/201506051435079426JN.png';
                            let imgUrl = CONSTANT.weChatBaseUrl + "static/logo.png";
                            
                            if (opt != '') {
                                if (opt.link) {
                                    // 页面分享
                                    link = CONSTANT.weChatBaseUrl + opt.link;
                                    desc = opt.desc;
                                    imgUrl = CONSTANT.weChatBaseUrl + opt.img;
                                } else {
                                    // 商品分享
                                    link = CONSTANT.weChatBaseUrl + '?#/commodity?goodsCommonid=' + opt.goodsCommonid;
                                    desc = opt.name;
                                    imgUrl = CONSTANT.imgBaseUrl + opt.img;
                                }
                            }

                            //分享朋友圈
                            wx.onMenuShareTimeline({
                                title: title,
                                link: link,
                                imgUrl: imgUrl, // 自定义图标
                                trigger: function (res) {
                                    // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容，因为客户端分享操作是一个同步操作，这时候使用ajax的回包会还没有返回.
                                    //alert('click shared');
                                },
                                success: function (res) {
                                    //alert('shared success');
                                    //some thing you should do
                                    if (opt != '' && opt.eggShared == 2) {
                                        localStorage.setItem('eggShared', "1"); 
                                        // 提示信息
                                        window.alert("感谢您分享商品，邀请您再次砸蛋，预祝您中奖！");
                                        // 刷新winegg页面
                                        window.location.reload();
                                    }
                                },
                                cancel: function (res) {
                                    //alert('shared cancle');
                                },
                                fail: function (res) {
                                    //alert(JSON.stringify(res));
                                }
                            });
                            //分享给好友
                            wx.onMenuShareAppMessage({
                                title: title, // 分享标题
                                desc: desc, // 分享描述
                                link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: imgUrl, // 自定义图标
                                type: 'link', // 分享类型,music、video或link，不填默认为link
                                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                                success: function () {
                                    // 用户确认分享后执行的回调函数
                                    if (opt != '' && opt.eggShared == 2) {
                                        localStorage.setItem('eggShared', "1");
                                        // 提示信息
                                        window.alert("感谢您分享商品，邀请您再次砸蛋，预祝您中奖！");
                                        // 刷新winegg页面
                                        window.location.reload();
                                    }
                                },
                                cancel: function () {
                                    // 用户取消分享后执行的回调函数
                                }
                            });
                        })
                    }
                }
            })
    }
}

//过滤
const getters = {
  /* count(state) {
   return state.count += 100;
   }*/
}

//异步改变状态
const actions = {
  memberDetail({commit}, opt) {
    return new Promise((resolve, reject) => {
      Vue.prototype.$axios.get(this.CONSTANT.wapiBaseUrl + 'member/memberDetail')
        .then((response) => {
          if (response.status == 200) {
            let email = response.data.object.memberEmail;
            if (email.indexOf('cofco.com') > 0) {
              commit('memberDetail', 1)
            }
          }
        })
    })
  }
}
export default new Vuex.Store({
  state,
  mutations,
  getters,
  actions
})